package cn.edu.sdjzu.xg23.kcsj01_backend.controller;



import cn.edu.sdjzu.xg23.kcsj01_backend.entity.User;
import cn.edu.sdjzu.xg23.kcsj01_backend.service.UserService;
import cn.edu.sdjzu.xg23.kcsj01_backend.utils.Result;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.edu.sdjzu.xg23.kcsj01_backend.utils.ResultCodeEnum.PARAM_PASSWORD_ERROR;


@Controller
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PreAuthorize("hasAuthority('system:user:search')")
    @PostMapping("/search")
    public Result selectUser(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestBody(required = false) User user) {
        PageInfo<User> pageInfo = userService.selectUser(pageNum, pageSize, user);
        return Result.success(pageInfo);
    }

    @PreAuthorize("hasAuthority('system:user:add')")
    @PostMapping("/add")
    public Result addUser(@RequestBody AddUserRequest request) {
        if (userService.addUser(request.getUser(),request.getRoleIds())) {
            return Result.success("增加成功");
        } else {
            return Result.error("500", "增加失败");
        }
    }
    @PreAuthorize("hasAuthority('system:user:delete')")
    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Long id) {
        if (userService.deleteUser(id)) {
            return Result.success("删除成功");
        } else {
            return Result.error("500", "删除失败");
        }
    }
    @PreAuthorize("hasAuthority('system:user:resetPassword')")
    @PutMapping("/resetPassword")
    public Result resetPassword(@RequestBody User user) {
        if (userService.resetPassword(user.getId())) {
            return Result.success("重置密码成功");
        } else {
            return Result.error("500", "重置密码失败");
        }
    }

    //    @PreAuthorize("hasAuthority('system:user:updatePassword')")
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordRequest request) {
        if (userService.updatePassword(request.getUser(),request.getOldPassword())){
            return Result.success("修改密码成功");
        }else {
            return Result.error(PARAM_PASSWORD_ERROR);
        }
    }





    public static @Data class AddUserRequest {
        private User user;
        private List<Long> roleIds;
    }

    public static @Data class UpdatePasswordRequest {
        private User user;
        private String oldPassword;
    }
}